package com.laoli.lab40;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * orTimeout() 示例
 */
public class OrTimeoutDemo {
    public static void main(String[] args) throws InterruptedException {
        // 异步任务(耗时2s)
        CompletableFuture.supplyAsync(() -> {
                    System.out.printf("【异步任务】开始：%s\n",LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                    try {
                        Thread.sleep(2000); // 休眠2s
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    return "异步任务结果"; // 返回结果
                }) //2s
                // 超时等待1s
                .orTimeout(1000, TimeUnit.MILLISECONDS)
                // 异常处理
                .exceptionally(exception -> {
                    if (exception instanceof TimeoutException) {
                        return "发生超时异常："+LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
                    }
                    return "发生其他异常";
                })
                // 输出任务结果(方法引用)
                .thenAccept(System.out::println);

        // 主线程休眠
        Thread.sleep(3000);
    }
}
